<template>
	<view style="height: 100%;">
		<view class="long-categories" id="scroll-panel">
			<view class="left">
				<scroll-view :scroll-with-animation="true" class="scroll-height" scroll-y :style="{height: scrollHeight + 'px'}">
					<view class="left-item" v-for="(item,index) in list" :key="index" :data-index="index" :id="'left-' + index"
						:class="{'left-item-active': index == active }" @click="(e) => categoryClick(item,index,e)">
						{{ item.text }}
					</view>
				</scroll-view>
			</view>
			<view class="right">
				<scroll-view scroll-y @scroll="scroll" :style="{height: scrollHeight + 'px'}" scroll-with-animation :scroll-into-view="scrollInto"
					@scrolltolower="scrollToBottom">
					<view class="right-container" v-for="(item,index) in list" :key="index" :id="'item-' + index">
						<view class="category-name" :id="`cid${ item.value }`">
							<view class="line"></view>
							<view class="txt">
								{{ item.text }}
							</view>
							<view class="line"></view>
						</view>
						<view class="category-content">
							<view v-for="(child, index1) in item.children" :key="index1" class="right-item"
								:class="{'right-item-active': child.checked, 'right-item-disable': child.disabled }"
								@click="itemClick(item, child, index, index1)">
								<view>{{ child.text }}</view>
							</view>
						</view>
					</view>
					<view class="fill-last" :style="{ height: fillHeight + 'px' }"></view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "category",
		data() {
			return {
				scrollHeight: 500,
				height: 0,
				active: 0,
				cIndex: '',
				topList: [],
				flag: false,
				scrollTopSize: 0,
				fillHeight: 0, // 填充高度，用于最后一项低于滚动区域时使用
				leftIndex: 0,
				topArr: [],
				scrollInto:''
			}
		},
		props: {
			list: {
				type: Array,
				default: () => {
					return []
				}
			},
			maxSelected: {
				type: [String, Number],
				default: '-1'
			}
		},
		computed:{
			/* 计算左侧滚动位置定位 */
			leftIntoView() {
				return `left-${this.leftIndex > 3 ? this.leftIndex - 3 : 0}`;
			}
		},
		// watch: {
		// 	list: {
		// 		handler(val) {
		// 			console.log(val)
		// 			this.$forceUpdate()
		// 		},
		// 		deep: true,
		// 	}
		// },
		//挂载后调用
		mounted() {
			// console.log(this.list)
			uni.getSystemInfo({
				success: res => {
					this.height = res.screenHeight - 630;
				}
			})
			this.getNodesInfo()
			setTimeout(() => {
				this.getSelectedCount()
			}, 500)
			
			/* 等待DOM挂载完成 */
			this.$nextTick(() => {
				/* 在非H5平台，nextTick回调后有概率获取到错误的元素高度，则添加200ms的延迟来减少BUG的产生 */
				setTimeout(() => {
					/* 等待滚动区域初始化完成 */
					this.initScrollView().then(() => {
						/* 获取列表数据，你的代码从此处开始 */
						// DOM 挂载后 再调用 getElementTop 获取高度的方法。
						this.getElementTop();
					});
				}, 200);
			});
		},
		methods: {
			/* 获取元素顶部信息 */
			getElementTop() {
				new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().selectAll('.right-container');
					view.boundingClientRect(data => {
						resolve(data);
					}).exec();
				}).then(res => {
					let topArr = res.map(item => {
						return item.top - this.scrollTopSize; /* 减去滚动容器距离顶部的距离 */
					});
					this.topArr = topArr;
	
					/* 获取最后一项的高度，设置填充高度。判断和填充时做了 +-20 的操作，是为了滚动时更好的定位 */
					let last = res[res.length - 1].height;
					if (last - 20 < this.scrollHeight) {
						this.fillHeight = this.scrollHeight - last + 20;
					}
				});
			},
			/* 初始化滚动区域 */
			initScrollView() {
				return new Promise((resolve, reject) => {
					let view = uni.createSelectorQuery().select('#scroll-panel');
					view.boundingClientRect(res => {
						this.scrollTopSize = res.top;
						this.scrollHeight = res.height;
						this.$nextTick(() => {
							resolve();
						});
					}).exec();
				});
			},
			Update() {
				this.getSelectedCount()
			},
			scroll(e) {
				if (this.flag) {
					this.flag = false
					return
				}
				let scrollTop = e.target.scrollTop
				for (let i = 0; i < this.topList.length; i++) {
					let h1 = this.topList[i]
					let h2 = this.topList[i + 1]
					if (scrollTop > h1 && scrollTop < h2) {
						this.active = i
					}
				}
				
				let top = e.detail.scrollTop
				let index = 0
				/* 查找当前滚动距离 */
				for (let i = this.topArr.length - 1; i >= 0; i--) {
					/* 在部分安卓设备上，因手机逻辑分辨率与rpx单位计算不是整数，滚动距离与有误差，增加2px来完善该问题 */
					if (top + 2 >= this.topArr[i]) {
						index = i
						break
					}
				}
				this.leftIndex = index < 0 ? 0 : index
			},
			categoryClick(category,index,e) {
				this.$nextTick(() => {
					this.cIndex = `cid${ category.id }`
					this.flag = true
				})
				this.cIndex = ''
				this.active = index
				let indexs = e.currentTarget.dataset.index;
				this.scrollInto = `item-${indexs}`;
			},
			// leftTap(e) {
			// 	let index = e.currentTarget.dataset.index;
			// 	this.scrollInto = `item-${index}`;
			// },
			itemClick(category, item, index, index1) {
				// console.log(category, item, index, index1)
				if (item.disabled) return
				let checked = !item.checked
				if (checked && this.maxSelected != '-1' && this.getValues().length >= Number(this.maxSelected)) {
					uni.showToast({
						icon: 'none',
						title: `最多可选${ this.maxSelected }个`
					})
					return
				}
				item.checked = checked;
				this.$forceUpdate()
				// this.list[index].children[index1].checked = checked

				// if (checked) {
				// 	category.selectedIds[item.value] = item
				// 	debugger
				// } else {
				// 	debugger
				// 	delete category.selectedIds[item.value]
				// }
				this.getSelectedCount();

			},

			// getActive() {
			// 	return {
			// 		index: this.active,
			// 		data: JSON.parse(JSON.stringify(this.list[this.active]))
			// 	}
			// },
			getValues() {
				let ids = []
				this.list.forEach(item => {

					item.children.forEach(res => {
						if (res.checked) {
							ids.push(res);
						}
					})

				})
				return ids
			},
			getSelectedCount() {
				let ids = this.getValues()
				this.$emit('change', JSON.parse(JSON.stringify(ids)))
			},

			getNodesInfo() {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.category-name').boundingClientRect().exec(res => {
					let nodes = res[0]
					this.topList = nodes.map(item => item.top)
				})
			},

			scrollToBottom() {
				setTimeout(() => {
					this.active = this.list.length - 1
				}, 50)
			},
			reload() {
				this.getNodesInfo()
			}
		},

	}
</script>

<style lang="less" scoped>
	.long-categories {
		display: flex;
		width: 100%;
		height: 100%;
		flex-wrap: wrap;
	}

	.left {
		width: 220rpx;
		height: 100%;
		background: #F1F2F6;

		scroll-view {
			height: calc(100vh - 340rpx - var(--status-bar-height));
		}
	}

	.left-item {
		width: 100%;
		padding: 20rpx 10rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		color: #333333;
		display: flex;
		align-items: center;
		justify-content: space-evenly;

		.num {
			width: 30rpx;
			height: 30rpx;
			line-height: 30rpx;
			background: #F67124;
			border-radius: 50%;
			color: #FFFFFF;
			font-size: 16rpx;
			font-weight: normal;
			text-align: center;
		}
	}

	.left-item-active {
		background: #FFFFFF;
		color: #1684FC;
		font-weight: bold;
	}

	.right {
		width: calc(100vw - 220rpx);
		background: #FFFFFF;
		height: 100%;

		scroll-view {
			height: calc(100vh - 340rpx - var(--status-bar-height));
		}
	}

	.right-container {
		.category-name {
			padding: 20rpx;
			text-align: center;

			.line {
				display: inline-block;
				width: 40rpx;
				border-top: 2rpx solid grey;
			}

			.txt {
				padding: 0 8rpx;
				display: inline-block;
				vertical-align: middle;
			}
		}

		.category-content {
			display: flex;
			flex-wrap: wrap;
			padding: 32rpx 18rpx 0 18rpx;
		}

	}

	.right-item {
		margin-left: 32rpx;
		margin-bottom: 42rpx;
		padding: 0 10rpx;
		height: 60rpx;
		line-height: 60rpx;
		background: #FFFFFF;
		border: 2rpx solid #999999;
		opacity: 1;
		border-radius: 8rpx;
		font-size: 28rpx;
		text-align: center;
		color: #333333;
		font-weight: 400;
	}

	.right-item-active {
		background-color: #1684FC;
		color: #FFFFFF;
	}

	.right-item-disable {
		background: #EFEFEF;
		color: #666666;
		border-color: #EFEFEF;
	}

	.right-item image {
		width: 50px;
		height: 50px;
	}

	.active {
		color: #F24544;
	}

	.padding {
		height: var(--status-bar-height);
		width: 100%;
		top: 0;
		position: fixed;
		background-color: #F24544;
	}
	.scroll-height {
		height: 100%;
	}
</style>
